package com.nnxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nnxy.mapper.StudentMapper;
import com.nnxy.pojo.PageResult;
import com.nnxy.pojo.Student;
import com.nnxy.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> findByPage(Integer page, Integer pageSize, String name, Integer degree, Integer id) {

        //1.设置PageHelper的分页参数，查询第几页，每页多少条数据
        PageHelper.startPage(page,pageSize);

        Page<Student> pageObj = studentMapper.findByPage(page, pageSize, name,  degree, id);

        //3.获取总条数和当前页数据列表
        long total = pageObj.getTotal();//本质原理：select count(*) from 表 where 条件
        List<Student> rows = pageObj.getResult();//本质原理：select * from 表 where 条件 limit ?,?

        for (Student student : rows) {
            if (student.getClazzName() == null) {
                student.setClazzName("没有加入任何班级");
            }
        }

        //4.封装PageResult对象，返回数据
        return new PageResult(rows,total);
    }

    @Override
    public void add(Student student) {
        //违纪次数默认为0
        student.setViolationCount((short) 0);
        //违纪分数默认为0
        student.setViolationScore((short) 0);
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        //如果没有加入班级，则默认加入未加入班级
        if (student.getClazzId() == null) {
            student.setClazzId(0);
        }

        studentMapper.insert(student);
    }
    public void deleteById(List<Integer> ids) {
        studentMapper.deleteById(ids);
    }

    @Override
    public Student findById(Integer id) {
        return studentMapper.findById(id);
    }

    @Override
    public void update(Student student) {

        student.setUpdateTime(LocalDateTime.now());

        studentMapper.update(student);
    }
}
